import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_study/utils/platform_util.dart';
import 'package:logger/logger.dart';

class Chapter1Page extends StatefulWidget {
  const Chapter1Page({Key? key}) : super(key: key);

  @override
  _Chapter1PageState createState() => _Chapter1PageState();
}

class _Chapter1PageState extends State<Chapter1Page> {
  final logger = Logger(printer: PrettyPrinter());
  Image? _image;

  String selectedDirStr = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("第一章 移动技术发展史"),
        leading: IconButton(
          icon: const Icon(Icons.home),
          onPressed: () => Navigator.of(context).pushNamed("/"),
        ),
      ),
      body: ListView(
        children: <Widget>[
          Container(
            child: ElevatedButton(
              onPressed: () => getFiles(),
              child: const Text("选择文件"),
            ),
            alignment: Alignment.center,
            height: 100,
            padding: const EdgeInsets.all(5),
          ),
          Container(
            child: _image ?? const Text("暂无图片"),
            height: 300,
            alignment: Alignment.topCenter,
            padding: const EdgeInsets.all(5),
          ),
          const SizedBox(height: 20),
          Container(
            child: ElevatedButton.icon(
              onPressed: () async {
                if (!PlatformUtil.isWeb) {
                  String? selectedDir =
                      await FilePicker.platform.getDirectoryPath();
                  logger.i("selectedDir $selectedDir");
                  var dir = Directory(selectedDir!);
                  setState(() {
                    selectedDirStr =
                        '目录: \r\n$selectedDir \r\n文件总数: ${dir.listSync().length}';
                  });
                  logger.i("文件总数: ${dir.listSync().length}");
                }
              },
              icon: const Icon(Icons.file_open),
              label: const Text("选择文件夹"),
            ),
            alignment: Alignment.topCenter,
            padding: const EdgeInsets.all(5),
          ),
          Container(
            child: selectedDirStr.isEmpty
                ? const Text("请选择目录")
                : Text(selectedDirStr),
            alignment: Alignment.topCenter,
            padding: const EdgeInsets.all(5),
          ),
        ],
      ),
    );
  }

  void getFiles() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: [
        'jpg',
        'png',
        'jpeg',
      ],
    );
    if (result != null) {
      var firstFile = result.files.first;
      setState(() {
        if (PlatformUtil.isWeb) {
          _image = Image.memory(firstFile.bytes!);
        } else {
          _image = Image.file(File(firstFile.path!));
        }
      });
    }
  }
}
